#include "widget.h"
#include "./ui_widget.h"
#include <QtSql>
#include <QMessageBox>
#include <QSqlTableModel>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle(QString("数据库可视化管理"));
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");//a
    db.setHostName("127.0.0.1");             //b
    db.setDatabaseName("test04");              //c
    db.setUserName("root");                  //d
    db.setPassword("123456");                //e
    if (!db.open()) {
        QMessageBox::critical(0, QObject::tr("Database Error"), db.lastError().text());
        return;
    }

    // 设置模型
    mod = new QSqlTableModel(this);
    mod->setTable("orders");

    // 把模型放在view
    ui->tableView->setModel(mod);

    // 显示模型里的数据
    mod->select();

    // 修改为中文
    /*
    mod->setHeaderData(0,Qt::Horizontal, "用户名");
    mod->setHeaderData(1,Qt::Horizontal, "密码");
    mod->setHeaderData(2,Qt::Horizontal, "真实姓名");
    mod->setHeaderData(3,Qt::Horizontal, "学号");
    mod->setHeaderData(4,Qt::Horizontal, "权限等级");
    */
    // 设置为手动提交
    mod->setEditStrategy(QSqlTableModel::OnManualSubmit);
    // 设置为只读（低权限的人不能改）
    // ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // this->showFullScreen();

}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_BtnAdd_clicked()
{
    QSqlRecord record = mod->record(); // 添加并获取空记录

    // 获取行号
    int row = mod->rowCount();

    // 插入记录
    mod->insertRecord(row, record);
}


void Widget::on_BtnSure_clicked()
{
    mod->submitAll();
}


void Widget::on_BtnCancel_clicked()
{
    mod->revertAll();
    mod->submitAll();
}


void Widget::on_BtnDel_clicked()
{
    // 获取选中模型
    QItemSelectionModel *SMod = ui->tableView->selectionModel();
    // 取出模型中的索引
    QModelIndexList List = SMod->selectedRows();
    // 删除所有选中行
    for(int i = 0; i < List.size(); i++){
        mod->removeRow(List.at(i).row());
    }
}


void Widget::on_BtnFind_clicked()
{
    QString str, str_ser, str_sort;
    str_ser = ui->lineEdit->text();
    str_sort = ui->FindSort->currentText();
    if(str_sort == "全部"){
        mod->setFilter("");
        mod->select();
    }
    else{
        if(str_sort == "真实姓名")
            str = QString ("realname = '%1'").arg(str_ser);
        else if(str_sort == "用户名")
            str = QString ("username = '%1'").arg(str_ser);
        else if(str_sort == "学号/教工号")
            str = QString ("id = '%1'").arg(str_ser);
        else if(str_sort == "用户权限")
            str = QString ("power = '%1'").arg(str_ser);
        else if(str_sort == "密码")
            str = QString ("password = '%1'").arg(str_ser);
        mod->setFilter(str);
        mod->select();
    }
}


void Widget::on_FindSort_activated(const QString &arg1)
{
    ui->BtnFind->setFocus();
}

